#include "sensor.h"

void error(const char *msg) { perror(msg); }

// Process for handling communication from anywhere to anywhere.
void *sender (void *t_data) {
  struct TDATA *tdata = (struct TDATA *) t_data; 
  struct sockaddr_in dest_addr;  // Holds address information. 
  struct hostent *server;        // Server information.

  // Set up generic datagram socket for sending.
  int sending_sock = socket(AF_INET, SOCK_DGRAM, FLAGS);
  if (FAILURE == sending_sock) SOCK_ERROR;
  server = gethostbyname("localhost");
  if (server == NULL) fprintf(stderr, "No such host.");
  bzero((char *) &dest_addr, sizeof(dest_addr));   
  bcopy((char *) server->h_addr, (char *)&dest_addr.sin_addr.s_addr, server->h_length);

  // Specify destination/port and connect/send.
  dest_addr.sin_family = AF_INET;
  dest_addr.sin_port   = htons(PORT+tdata->dest);
  if (FAILURE == connect(sending_sock, (struct sockaddr *) &dest_addr, sizeof(dest_addr))) 
    CONN_ERROR;
  send(sending_sock, tdata->msg, strlen(tdata->msg), FLAGS);
  if (tdata->type == ACK) return;

  // Wait for acknowledgement.
  char ack[BSIZE];
  int receiving_sock = socket(AF_INET, SOCK_DGRAM, FLAGS);
  if (FAILURE == receiving_sock) SOCK_ERROR;
  if (bind(receiving_sock, (struct sockaddr *) &dest_addr, sizeof(dest_addr) == FAILURE)) BIND_ERROR;
  listen(receiving_sock,5);
  socklen_t dest_len = sizeof(dest_addr);
  int listening_sock = accept(receiving_sock, (struct sockaddr *) &dest_addr, &dest_len);
  if (listening_sock == FAILURE) ACPT_ERROR;
  bzero(ack, BSIZE);
  while (read(listening_sock, ack, BSIZE) != FAILURE) { 
   if (NULL == strstr(ack, "ACK")) {
    // Create handler thread.
   }
  }
  
  close(sending_sock);
  close(receiving_sock);
  close(listening_sock);
  return;
}

